package com.zjw.mycoolweather.ui.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.zjw.mycoolweather.R;
import com.zjw.mycoolweather.db.Weather;
import com.zjw.mycoolweather.ui.service.AutoUpdateService;
import com.zjw.mycoolweather.util.HttpUtil;
import com.zjw.mycoolweather.util.Utility;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 用于显示天气信息的活动
 */

public class WeatherActivity extends AppCompatActivity {

    @BindView(R.id.tv_title_city)
    TextView mTvTitleCity;
    @BindView(R.id.tv_title_update_time)
    TextView mTvTitleUpdateTime;
    @BindView(R.id.tv_now_degree)
    TextView mTvNowDegree;
    @BindView(R.id.tv_now_weather_info)
    TextView mTvNowWeatherInfo;
    @BindView(R.id.ll_forecast)
    LinearLayout mLlForecast;
    @BindView(R.id.tv_aqi)
    TextView mTvAqi;
    @BindView(R.id.tv_pm25)
    TextView mTvPm25;
    @BindView(R.id.tv_comfort)
    TextView mTvComfort;
    @BindView(R.id.tv_car_wash)
    TextView mTvCarWash;
    @BindView(R.id.tv_sport)
    TextView mTvSport;
    @BindView(R.id.sv_weather)
    ScrollView mSvWeather;
    @BindView(R.id.iv_bing_pic)
    ImageView mIvBingPic;
    @BindView(R.id.srl_refresh)
    public SwipeRefreshLayout mSrlRefresh;
    @BindView(R.id.bt_nav)
    Button mBtNav;
    @BindView(R.id.dl)
    public DrawerLayout mDl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //背景图和状态栏融合
        if (Build.VERSION.SDK_INT >= 21) {//5.0以上才支持
            View decorView = getWindow().getDecorView();//获取DecorView
            //改变系统UI显示，传入的参数表示活动的布局会显示在状态栏上面
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);//状态栏设置为透明色
        }

        //设置布局，与黄油刀绑定
        setContentView(R.layout.activity_weather);
        ButterKnife.bind(this);

        final String weatherId;
        //获取本地天气数据缓存
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        String weatherString = sharedPreferences.getString("weather", null);
        if (weatherString != null) {
            //有缓存时直接解析天气数据
            Weather weather = Utility.handleWeatherResponse(weatherString);
            weatherId = weather.getHeWeather().get(0).getBasic().getId();
            showWeatherInfo(weather);
        } else {
            //无缓存时去服务器查询天气
            weatherId = getIntent().getStringExtra("weather_id");
            mSvWeather.setVisibility(View.INVISIBLE);//scrollview先隐藏，不然请求数据时界面没数据
            requestWeather(weatherId);
        }

        //获取必应每日图片本地缓存
        String bingPic = sharedPreferences.getString("bing_pic", null);
        if (bingPic != null) {
            //有缓存时直接设置背景图片
            Glide.with(this).load(bingPic).into(mIvBingPic);
        } else {
            //无缓存时去服务器获取图片
            loadBingPic();
        }

        //下拉刷新相关设置
        mSrlRefresh.setColorSchemeResources(R.color.colorPrimary);
        mSrlRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                requestWeather(weatherId);
            }
        });

        //打开侧滑菜单
        mBtNav.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDl.openDrawer(GravityCompat.START);
            }
        });
    }

    /**
     * 根据天气id请求城市天气信息
     */
    public void requestWeather(String weatherId) {
        String weatherUrl = "http://guolin.tech/api/weather/?cityid=" + weatherId + "&key=24c232ca7bde41cf824dec83f4f411b8";
        HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String responseText = response.body().string();
                final Weather weather = Utility.handleWeatherResponse(responseText);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (weather != null && "ok".equals(weather.getHeWeather().get(0).getStatus())) {
                            //保存到本地缓存
                            SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
                            editor.putString("weather", responseText);
                            editor.apply();
                            showWeatherInfo(weather);
                        } else {
                            Toast.makeText(WeatherActivity.this, "获取天气信息失败", Toast.LENGTH_SHORT).show();
                        }
                        mSrlRefresh.setRefreshing(false);
                    }
                });
            }

            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(WeatherActivity.this, "获取天气信息失败", Toast.LENGTH_SHORT).show();
                        mSrlRefresh.setRefreshing(false);
                    }
                });
            }
        });
        loadBingPic();
    }

    /**
     * 处理并展示Weather实体类中的数据
     *
     * @param weather
     */
    private void showWeatherInfo(Weather weather) {
        if (weather != null && "ok".equals(weather.getHeWeather().get(0).getStatus())) {
            String cityName = weather.getHeWeather().get(0).getBasic().getCity();
            String updateTime = weather.getHeWeather().get(0).getBasic().getUpdate().getLoc().split(" ")[1];
            String degree = weather.getHeWeather().get(0).getNow().getTmp() + "°C";
            String weatherInfo = weather.getHeWeather().get(0).getNow().getCond().getTxt();

            mTvTitleCity.setText(cityName);
            mTvTitleUpdateTime.setText("更新时间:" + updateTime);
            mTvNowDegree.setText(degree);
            mTvNowWeatherInfo.setText(weatherInfo);

            mLlForecast.removeAllViews();
            for (Weather.HeWeatherBean.DailyForecastBean dailyForecastBean : weather.getHeWeather().get(0).getDaily_forecast()) {

                View view = LayoutInflater.from(this).inflate(R.layout.forecast_item, mLlForecast, false);

                TextView tvForecastItemDate = (TextView) view.findViewById(R.id.tv_forecast_item_date);
                TextView tvForecastItemInfo = (TextView) view.findViewById(R.id.tv_forecast_item_info);
                TextView tvForecastItemMax = (TextView) view.findViewById(R.id.tv_forecast_item_max);
                TextView tvForecastItemMin = (TextView) view.findViewById(R.id.tv_forecast_item_min);

                tvForecastItemDate.setText(dailyForecastBean.getDate());
                tvForecastItemInfo.setText(dailyForecastBean.getCond().getTxt_d());
                tvForecastItemMax.setText(dailyForecastBean.getTmp().getMax());
                tvForecastItemMin.setText(dailyForecastBean.getTmp().getMin());

            mLlForecast.addView(view);
            }

            if (weather.getHeWeather().get(0).getAqi() != null) {
            mTvAqi.setText(weather.getHeWeather().get(0).getAqi().getCity().getAqi());
            mTvPm25.setText(weather.getHeWeather().get(0).getAqi().getCity().getPm25());
            }

            String comfort = "舒适度：" + weather.getHeWeather().get(0).getSuggestion().getComf().getTxt();
            String carWash = "洗车指数：" + weather.getHeWeather().get(0).getSuggestion().getCw().getTxt();
            String sport = "运动建议：" + weather.getHeWeather().get(0).getSuggestion().getSport().getTxt();

            mTvComfort.setText(comfort);
            mTvCarWash.setText(carWash);
            mTvSport.setText(sport);

            mSvWeather.setVisibility(View.VISIBLE);

            //开启服务
            Intent intent=new Intent(this, AutoUpdateService.class);
            startService(intent);
        } else {
            Toast.makeText(WeatherActivity.this, "获取天气信息失败", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 加载必应每日一图
     */
    private void loadBingPic() {
        String requestBingPic = "http://guolin.tech/api/bing_pic";
        HttpUtil.sendOkHttpRequest(requestBingPic, new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String bingPic = response.body().string();
                if(!TextUtils.isEmpty(bingPic)){
                    SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
                    editor.putString("bing_pic", bingPic);
                    editor.apply();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Glide.with(WeatherActivity.this).load(bingPic).into(mIvBingPic);
                        }
                    });
                }
                else{
                    final String bingPic2="http://api.dujin.org/bing/1920.php";//备用
                    SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
                    editor.putString("bing_pic", bingPic2);
                    editor.apply();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Glide.with(WeatherActivity.this).load(bingPic2).into(mIvBingPic);
                        }
                    });
                }
            }

            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }
        });
    }
}
